package io.renren.modules.admin.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.admin.entity.AccountContentEntity;
import io.renren.modules.admin.entity.AccountUpEntity;
import io.renren.modules.admin.entity.vo.AccountTaskReqVo;
import io.renren.modules.admin.entity.vo.DevHttpJsonVo;
import io.renren.modules.admin.entity.vo.SendTaskVo;
import io.renren.modules.admin.service.AccountContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.admin.service.AccountUpService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import org.springframework.web.client.RestTemplate;


/**
 * 
 * @author fangzq
 * @email canglx1996@163.com
 * @date 2020-12-11 19:53:19
 */
@RestController
@RequestMapping("admin/accountup")
public class AccountUpController {
    @Autowired
    private AccountUpService accountUpService;

    @Autowired
    private AccountContentService accountContentService;
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("api/getContext")
    public R getContext(String desc,Long userId) {
        AccountContentEntity accountContentEntity = this.accountContentService.queryByDesc(desc,"1003",userId);
        if (accountContentEntity == null) {
            return R.error("没有对应评论");
        }
        String content = accountContentEntity.getContent();
        String[] split = content.split("\\|");
        String jsonString = JSON.toJSONString(split);
        return R.ok().put("context", jsonString);
    }

    /**
     * 用于发送多个任务
     */
    @PostMapping("api/taskLists")
    public R list2(@RequestBody AccountUpEntity accountUpEntity) {
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登陆信息出错，请重新登陆");
        }
        String phoneIds = accountUpEntity.getPhoneIds();
        String replace = phoneIds.trim().replace("|", ",");

        AccountTaskReqVo taskReqVo = new AccountTaskReqVo();
        taskReqVo.setApiUrl("http://47.107.104.4:8080/renren-fast/admin/accountup/api/getContext?desc="+accountUpEntity.getCommentType()+"&userId="+userId);
        taskReqVo.setCommentType(accountUpEntity.getCommentType());
        taskReqVo.setCommentDelayStart(accountUpEntity.getCommentDelayStart());
        taskReqVo.setCommentDelayEnd(accountUpEntity.getCommentDelayEnd());
        taskReqVo.setRateComment(accountUpEntity.getRateComment());
        taskReqVo.setRateLike(accountUpEntity.getRateLike());
        taskReqVo.setAlarmTimeDelay(accountUpEntity.getAlarmTimeDelay());

        SendTaskVo map1 = new SendTaskVo(AccountUpEntity.OPTTYPE,taskReqVo);

        String jsonString = JSON.toJSONString(map1);

        String url = "http://dou.shciyun.com/open/common/send/tasks";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

        // 封装数据
        map.add("data", jsonString);
        map.add("deviceIds",replace);
        map.add("type", "1");
        map.add("userId", String.valueOf(userId));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );

        // 发送任务之后，保存任务到数据库
//            accountUpEntity.setPhoneId(Long.parseLong(freePhoneNumList.get(i)));
        accountUpEntity.setUserId(userId);


        accountUpEntity.setPhoneIds(replace);
        accountUpEntity.setCreateTime(new Date());
        accountUpService.save(accountUpEntity);

        return R.ok();
    }

    /**
     * 用于接收任务
     */
    @PostMapping("api/taskList")
    public R list(@RequestBody AccountUpEntity accountUpEntity){
        //TODO 自己封装请求json 不用ManagerTaskReqVo了
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        AccountTaskReqVo taskReqVo = new AccountTaskReqVo();
        taskReqVo.setApiUrl("http://47.107.104.4:8080/renren-fast/admin/accountup/api/getContext?desc="+accountUpEntity.getCommentType()+"&userId="+userId);
        taskReqVo.setCommentType(accountUpEntity.getCommentType());
        taskReqVo.setCommentDelayStart(accountUpEntity.getCommentDelayStart());
        taskReqVo.setCommentDelayEnd(accountUpEntity.getCommentDelayEnd());
        taskReqVo.setRateComment(accountUpEntity.getRateComment());
        taskReqVo.setRateLike(accountUpEntity.getRateLike());
        taskReqVo.setAlarmTimeDelay(accountUpEntity.getAlarmTimeDelay());
        taskReqVo.setTaskName(accountUpEntity.getWordName());


        SendTaskVo map1 = new SendTaskVo(AccountUpEntity.OPTTYPE,taskReqVo);

        String jsonString = JSON.toJSONString(map1);

        String url = "http://dou.shciyun.com/open/common/send/task";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        HttpMethod method = HttpMethod.POST;
        MultiValueMap<String, String> map= new LinkedMultiValueMap<>();

        // 封装数据
        map.add("data", jsonString);
        map.add("deviceId", accountUpEntity.getPhoneIds().toString());
        map.add("type", "2");
        map.add("userId", String.valueOf(userId));

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        ResponseEntity<DevHttpJsonVo> response = this.restTemplate.exchange( url,method, request , DevHttpJsonVo.class );
        accountUpEntity.setUserId(userId);
        // 发送任务之后，保存任务到数据库
        accountUpService.save(accountUpEntity);

        if (response.getBody().getCode() == 200) {
            return R.ok();
        }else {
            return R.error(response.getBody().getMsg());
        }
    }

    /**
     * 查询所有的评论描述
     */
    @RequestMapping("/commentType/list")
    public R queryDesc(){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        List<String> descs = this.accountContentService.queryDesc(userId);
        return R.ok().put("list", descs);
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        PageUtils page = accountUpService.queryPage(params,userId);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		AccountUpEntity accountUp = accountUpService.getById(id);

        return R.ok().put("accountUp", accountUp);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody AccountUpEntity accountUp){
        accountUp.setCreateTime(new Date());
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        accountUp.setUserId(userId);
		accountUpService.save(accountUp);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody AccountUpEntity accountUp){
        Long userId = ShiroUtils.getUserId();
        if (userId == null) {
            return R.error("登录信息出错，请重新登录");
        }
        accountUp.setUserId(userId);
		accountUpService.updateById(accountUp);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
		accountUpService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
